﻿namespace LogManager.Utils.Authentification
{
    using LogManager.TestUtility;
    using NUnit.Framework;
    using System;
    using System.ComponentModel;
    using System.Net;
    using System.Security.Principal;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class TestImpersonator
    {
        public const string USERNAME = "nouveauUser";
        public const string PASSWORD = "MotDePasse";

        [SetUp]
        public void Init()
        {
            UserManagement.DeleteIfExists(USERNAME);
            UserManagement.CreateLocalUserAccount(USERNAME, PASSWORD);
        }

        [TearDown]
        public void CleanUp()
        {
            UserManagement.DeleteIfExists(USERNAME);
        }

        [Test]
        public void Impersonator_Ctor_impersonateUser_ContextIsImpersonated()
        {
            var originalIdentity = WindowsIdentity.GetCurrent().Name;
            using (var imp = new Impersonator(USERNAME, null, PASSWORD))
            {
                var impersonated = WindowsIdentity.GetCurrent().Name;
                Assert.AreEqual(Environment.MachineName + @"\" + USERNAME, impersonated);
            }
            Assert.AreEqual(originalIdentity, WindowsIdentity.GetCurrent().Name);
        }

        [Test]
        public void Impersonator_Ctor_impersonateUserNetworkCredentials_ContextIsImpersonated()
        {
            var originalIdentity = WindowsIdentity.GetCurrent().Name;
            var credentials = new NetworkCredential(USERNAME, PASSWORD);
            using (var imp = new Impersonator(credentials))
            {
                var impersonated = WindowsIdentity.GetCurrent().Name;
                Assert.AreEqual(Environment.MachineName + @"\" + USERNAME, impersonated);
            }
            Assert.AreEqual(originalIdentity, WindowsIdentity.GetCurrent().Name);
        }

        [Test]
        public void Impersonator_Ctor_impersonateUserBadCredentials_ThrowsException()
        {
            Assert.Throws<Win32Exception>(() =>
            {
                using (var imp = new Impersonator("badUsename", null, PASSWORD))
                {
                }
            });

        }
    }
}
